// src/stores/authStore.js
import { defineStore } from 'pinia';

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: localStorage.getItem('token') || null,
    id: localStorage.getItem('id') || null,
    username: localStorage.getItem('username') || null,
    isLoggedIn: !!localStorage.getItem('token'),
  }),

  actions: {
    // 登录成功时调用
    login({ token, id, username }) {
      this.token = token;
      this.id = id;
      this.username = username;
      this.isLoggedIn = true;

      localStorage.setItem('token', token);
      localStorage.setItem('id', id);
      localStorage.setItem('username', username);
    },

    // 退出登录时调用
    logout() {
      this.token = null;
      this.id = null;
      this.username = null;
      this.isLoggedIn = false;

      localStorage.removeItem('token');
      localStorage.removeItem('id');
      localStorage.removeItem('username');
    },
  },
});